<template>
    <div class="divClass">
        <Form ref="formItem" :model="formItem" :rules="ruleForm" label-width="120">
            <Row>
                <Col span="16" offset="4">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title" style="height:35px;margin-top:5px">
                            <label>请搜索患者信息：</label>
                            <AutoComplete
                                    clearable
                                    ref="autoComplete"
                                    v-model="searchValue"
                                    icon="ios-search"
                                    placeholder="姓名 / 手机 / 病历号"
                                    style="width:250px"
                                    @on-select="selectOption"
                                    @keyup.enter.native="search">
                                <!--<div>-->
                                    <!--<Option v-if="patients.length === 0">-->
                                        <!--<span class="demo-auto-complete-title">暂无结果</span>-->
                                    <!--</Option>-->
                                    <!--<Option v-if="patients.length > 1" v-for="item in patients" :value="item.id" :key="item.id">-->
                                        <!--<Row>-->
                                            <!--<Col span="12">-->
                                                <!--<span class="demo-auto-complete-title">{{ item.name }}</span>-->
                                            <!--</Col>-->
                                            <!--<Col span="12">-->
                                                <!--<span class="demo-auto-complete-count">{{ item.medicalNumber }}</span>-->
                                            <!--</Col>-->
                                        <!--</Row>-->
                                    <!--</Option>-->
                                <!--</div>-->
                            </AutoComplete>
                            <Button type="ghost" @click="searchReservation">预约查询</Button>
                            <!--<Dropdown placement="bottom-start" @on-click="clickDropdown">-->
                              <!--<Button type="ghost">-->
                                <!--预约查询-->
                                <!--<Icon type="arrow-down-b"></Icon>-->
                              <!--</Button>-->
                              <!--<DropdownMenu slot="list">-->
                                <!--&lt;!&ndash;<p>常用于各种自定义下拉内容的场景。</p>&ndash;&gt;-->
                                <!--<div style="text-align: right;margin:10px;">-->
                                  <!--&lt;!&ndash;<Button type="primary" @click="handleClose">关闭</Button>&ndash;&gt;-->
                                  <!--<Table border :columns="reservationColumns" :data="reservations"></Table>-->
                                <!--</div>-->
                              <!--</DropdownMenu>-->
                            <!--</Dropdown>-->
                        </p>
                        <Card :bordered="false" :dis-hover="true">
                            <Row style="font-size: 16px; font-weight: bold;">
                                <Col :span="5" :offset="1">病历号：<a href="#">{{patient.medicalNumber}}</a></Col>
                                <Col :span="6">患者姓名：<a href="#">{{patient.name}}</a></Col>
                                <Col :span="6">患者昵称：<a href="#">{{patient.nickName}}</a></Col>
                                <Col :span="6">患者性别：<a href="#">{{patient.sex | sexFilter}}</a></Col>
                            </Row>
                            <br/>
                            <Row style="font-size: 16px; font-weight: bold;">
                                <Col :span="5" :offset="1">手机号码：<a href="#">{{patient.phone}}</a></Col>
                                <Col :span="6">出生日期：<a href="#">{{patient.birthday}}</a></Col>
                                <Col :span="6">微信号码：<a href="#">{{patient.wechat}}</a></Col>
                                <Col :span="6">现住址：<a href="#">{{patient.address}}</a></Col>
                            </Row>
                        </Card>
                    </Card>
                    <Row>
                        <Col span="24">
                            <Card :bordered="false" :dis-hover="true">
                                <p slot="title">
                                    请填写预约信息：
                                </p>
                                <Row>
                                    <Col span="12">
                                        <FormItem label="问题描述：">
                                            <Input v-model="formItem.description" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                        </FormItem>
                                    </Col>
                                    <Col span="12">
                                        <FormItem label="可能诊断：">
                                            <Input v-model="formItem.diagnosis" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="12">
                                        <FormItem label="承诺备注：">
                                            <Input v-model="formItem.promise" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                        </FormItem>
                                    </Col>
                                    <Col span="12">
                                        <FormItem label="预约备注：">
                                            <Input v-model="formItem.note" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="8">
                                        <FormItem label="预约类型：" prop="type">
                                            <Select v-model="formItem.type" clearable @on-change="changeType">
                                                <Option value="1">复诊</Option>
                                                <Option value="2">新诊</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="8">
                                        <FormItem label="处理方式：" prop="process">
                                            <Select v-model="formItem.process" clearable>
                                                <Option value="1">电话随访</Option>
                                                <Option value="2">预约到店</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <!--<Col span="8">-->
                                        <!--<FormItem label="提醒方式：" prop="remind">-->
                                            <!--<Select v-model="formItem.remind" clearable>-->
                                                <!--<Option value="1">短信</Option>-->
                                                <!--<Option value="2">微信</Option>-->
                                                <!--<Option value="3">电话</Option>-->
                                            <!--</Select>-->
                                        <!--</FormItem>-->
                                    <!--</Col>-->
                                    <Col span="8">
                                        <FormItem label="预约时间：">
                                            <Row>
                                                <Col span="11">
                                                    <DatePicker v-model="formItem.appDate" style="width: 100%" clearable placement="top" @on-change="changeDate" format="yyyy-MM-dd" type="date" placeholder="请选择日期"></DatePicker>
                                                </Col>
                                                <Col span="2" align="center">-</Col>
                                                <Col span="11">
                                                    <Select v-model="formItem.appTime" style="width: 100%" clearable placement="top" @on-change="changeTime">
                                                        <Option v-for="(item,index) in schedules" :key="index" :value="item">{{ item }}</Option>
                                                    </Select>
                                                </Col>
                                            </Row>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="8">
                                        <FormItem label="预约护士：" prop="nurseId">
                                            <Select v-model="formItem.nurseId" clearable placement="top">
                                                <Option v-for="item in healthcare" v-if="item.job === 2" :value="item.id" :key="item.id">{{ item.username }}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="8">
                                        <FormItem label="预约医生：" prop="doctorId">
                                            <Select v-model="formItem.doctorId" clearable placement="top">
                                                <Option v-for="item in healthcare" v-if="item.job === 1 && item.isExpert !== 1" :value="item.id" :key="item.id">{{ item.username }}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="8">
                                        <FormItem label="预约专家：" prop="expertId">
                                            <Select v-model="formItem.expertId" clearable placement="top">
                                                <Option v-for="item in healthcare" v-if="item.job === 1 && item.isExpert === 1" :value="item.id" :key="item.id">{{ item.username }}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span="24">
                                        <Card :bordered="false" :dis-hover="true">
                                            <p slot="title">&nbsp;</p>
                                            <p align="right">
                                                <Button @click="save" type="primary" size="large" icon="android-checkmark-circle">确认预约</Button>
                                            </p>
                                        </Card>
                                    </Col>
                                </Row>
                            </Card>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </Form>
        <Modal v-model="showPatients" :closable='false' :mask-closable=true :width="800">
            <h3 slot="header" style="color:#2D8CF0">请选择预约患者</h3>
            <Table border :columns="patientColumns" :data="patients"></Table>
            <div slot="footer">
            </div>
        </Modal>
        <Modal v-model="showReservation" :closable='false' :mask-closable=true :width="1000">
          <h3 slot="header" style="color:#2D8CF0">预约记录</h3>
          <!--<Table border :columns="reservationColumns" :data="reservations"></Table>-->
          <iview-table
                  ref="table"
                  :baseURL="queryModel1.baseURL"
                  :menuId="dataModel1.menuId"
                  :columns="dataModel1.columns"
                  :order="dataModel1.order"
                  :pageNumber="pageModel1.pageNumber"
                  :pageSize="pageModel1.pageSize"
                  :defaultFilters="queryModel1.defaultFilters"
                  v-on="{changeSelect:changeSelect,changeTotalSize:changeTotalSize}">
          </iview-table>
            <br>
            <iview-page
                    :totalSize="pageModel1.totalSize"
                    :pageNumber="pageModel1.pageNumber"
                    :pageSize="pageModel1.pageSize"
                    :pageSizeOpts="pageModel1.pageSizeOpts"
                    v-on="{changePageNumber:changePageNumber,changePageSize:changePageSize}">
            </iview-page>
          <div slot="footer">
          </div>
        </Modal>
    </div>
</template>

<script>
import iviewTable from '@/view/common/table/Table.vue';
import iviewPage from '@/view/common/page/Page.vue';
import Table from "../../../common/table/Table";
export default {
    components: {
        Table,
        iviewTable,
        iviewPage
    },
    data () {
        return {
            searchValue: '',
            // 考勤
            attendanceURL: '/user/attendance',
            // 预约
            reservationURL: '/user/reservation',
            selectRows: [],
            showTag: false,
            showPatients: false,
            showReservation:  false,
            schedules: [],
            patient: {},
            healthcare: [],
            data: [],
            appointmentDate: '',
            appointmentTime: '',
            // 预约信息
            formItem: {
                id: '',
                patientId: '',
                patientName: '',
                medicalNumber: '',
                type: '',
                description: '',
                diagnosis: '',
                promise: '',
                remind: '',
                process: '',
                doctorId: '',
                doctorName: '',
                nurseId: '',
                nurseName: '',
                expertId: '',
                expertName: '',
                appointment: '',
                appointmentStr: '',
                appDate: '',
                appTime: '',
                note: ''
            },
            ruleForm: {
            },
            // 查询模型
            queryModel: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/patient',
                searchValue: ''
            },
            // 数据模型
            dataModel: {
                menuId: 101,
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title: '预约类型',
                        key: 'type',
                        render: (h, params) => {
                            let temp = params.row.type
                            if (temp === '1') {
                                temp = '复诊'
                            } else if (temp === '2') {
                                temp = '新诊'
                            }
                            return h('span', temp)
                        }
                    },
                    {
                        title: '提醒方式',
                        key: 'remind',
                        render: (h, params) => {
                            let temp = params.row.type
                            if (temp === '1') {
                                temp = '短信'
                            } else if (temp === '2') {
                                temp = '微信'
                            } else if (temp === '3') {
                                temp = '电话'
                            }
                            return h('span', temp)
                        }
                    },
                    {
                        title: '处理方式',
                        key: 'process',
                        render: (h, params) => {
                            let temp = params.row.process
                            if (temp === '1') {
                                temp = '电话随访'
                            } else if (temp === '2') {
                                temp = '预约到店'
                            }
                            return h('span', temp)
                        }
                    },
                    {
                        title: '预约时间',
                        key: 'appointment',
                    },
                    {
                        title: '预约医生',
                        key: 'doctorName',
                    },
                    {
                        title: '预约护士',
                        key: 'nurseName',
                    }
                ],
                order: 'creation_time desc'
            },
            patients: [],
            patientColumns: [
                {
                    title: '患者姓名',
                    key: 'name',
                },
                {
                    title: '病历号',
                    key: 'medicalNumber',
                },
                {
                    title: '出生日期',
                    key: 'birthday',
                },{
                    title: '联系方式',
                    key: 'phone',
                },
                {
                    title: '操作',
                    width: 150,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'info',
                                    size: 'default'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.select(params.row)
                                    }
                                }
                            }, '选择')
                        ]);
                    }
                }
            ],
            queryModel1: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/reservation',
                defaultFilters: [
                ]
            },
            dataModel1: {
                menuId: -1,
                columns: [
                    {
                        title: '预约时间',
                        key: 'appointment',
                        type: 'date',
                        sortable: true,
                        width: 150,
                    },{
                        title: '预约患者',
                        key: 'patientName',
                        sortable: true,
                        width: 120,
                    },{
                        title: '病历号',
                        key: 'medicalNumber',
                        sortable: true,
                        width: 150,
                    },{
                        title: '预约类型',
                        key: 'type',
                        sortable: true,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.type
                            if (temp === 1) {
                                temp = '复诊预约'
                                color = '#2d8cf0'
                            } else if (temp === 2) {
                                temp = '新诊预约'
                                color = '#19be6b'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    },
                    {
                        title: '处理方式',
                        key: 'process',
                        sortable: true,
                        render: (h, params) => {
                            let color = ''
                            let temp = params.row.process
                            if (temp === 1) {
                                temp = '电话随访'
                                color = '#19be6b'
                            } else if (temp === 2) {
                                temp = '预约到店'
                                color = '#2d8cf0'
                            }
                            return h('Tag',{
                                props: {
                                    // type: 'border',
                                    color: color
                                }
                            }, temp)
                        }
                    },{
                        title: '预约医生',
                        key: 'doctorName',
                        sortable: true,
                    },{
                        title: '预约护士',
                        key: 'nurseName',
                        sortable: true
                    },{
                        title: '预约备注',
                        key: 'note',
                        // width: 200
                    }
                ],
                order: 'appointment desc'
            },
            pageModel1: {
                totalSize: 0,
                pageNumber: 1,
                pageSize: 10,
                pageSizeOpts: [10, 50, 100, 500]
            }
        }
    },
    filters: {
        nameFilter (value) {
            let temp = ''
            if (!value) {
                temp = '请选择患者'
            } else {
                temp += value + ' - 基本资料'
            }
            return temp
        },
        sexFilter (value) {
            let temp = ''
            if (value === 1) {
                temp = '男'
            } else if (value === 2) {
                temp = '女'
            }
            return temp
        }
    },
    methods: {
        searchReservation () {
            if (this.patient.id && this.patient.id !== '') {
                this.queryModel1.defaultFilters.length = []
                this.queryModel1.defaultFilters.push({'field': 'record_type', 'value1': 0, 'operate': '=='})
                this.queryModel1.defaultFilters.push({'field': 'status', 'value1': 5, 'operate': '!='})
                this.queryModel1.defaultFilters.push({'field': 'patient_id', 'value1': this.patient.id, 'operate': '=='})
                this.$refs.table.refresh()
                this.showReservation = true
            } else {
                this.$bus.alert('warning', '请先选择预约患者')
            }
        },
        select (row) {
            this.patient = row
            this.formItem.patientId = row.id
            this.formItem.patientName = row.name
            this.formItem.medicalNumber = row.medicalNumber
            this.$bus.init(this.formItem, ['patientId', 'patientName', 'medicalNumber'])
            this.schedules = []
            this.healthcare = []
            this.reset()
            this.showPatients = false
        },
        // 调用后台查询
        search () {
            if (this.$route.query.id) {
                this.$bus.modal('warning', '系统提示', '重新预约或者再次预约时不允许变更预约患者')
                this.searchValue = this.$route.query.patientName
                return
            }
            let url = '/user/patient/search'
            this.$ajax.post(url, this.addFilter(this.searchValue, 'name', 'phone', 'medical_number')).then(response => {
                let {code, data} = response.data
                if (code === 0) {
                    if (data.length > 0) {
                        if (data.length === 1) {
                            this.patient = data[0]
                            this.formItem.patientId = data[0].id
                            this.formItem.patientName = data[0].name
                            this.formItem.medicalNumber = data[0].medicalNumber
                            this.$bus.init(this.formItem, ['patientId', 'patientName', 'medicalNumber'])
                            this.schedules = []
                            this.healthcare = []
                            this.reset()
                        } else {
                            this.patients = data
                            this.showPatients = true
                        }
                    } else {
                        this.$bus.modal('warning', '系统提示', '未查询到患者信息')
                    }
                }
            })
        },
        addFilter (val, ...fields) {
            let queryModel = {
                mode: 'or',
                pageNumber: 1,
                pageSize: 10,
                order: 'id',
                filters: []
            }
            for (let field of fields) {
                let filterModel = {'field': field, 'value1': val, 'operate': 'LIKE'}
                queryModel.filters.push(filterModel)
            }
            return queryModel
        },
        selectOption (value) {
            if (value && value !== '') {
                this.searchValue = ''
                let url = '/user/patient/findById/' + value
                this.$ajax.get(url).then((response) => {
                    let {code, data} = response.data
                    if (code === 0) {
                        this.showTag = true
                        this.patient = data
                        this.searchValue = data.name
                        this.formItem.patientId = data.id
                        this.formItem.patientName = data.name
                        this.formItem.medicalNumber = data.medicalNumber
                        this.$bus.init(this.formItem, ['patientId', 'patientName', 'medicalNumber'])
                        this.schedules = []
                        this.healthcare = []
                        this.patients = []
                        this.reset()
                    }
                })
            } else {
                this.showTag = false
                this.patient = {}
            }
        },
        changeType (val) {
            this.formItem.appTime = ''
            if (val && val !== '') {
                let url = '/user/sysConfig/getSchedule/' + val
                this.$ajax.get(url).then(response => {
                    let {code, data, msg} = response.data
                    if (code === 0) {
                        this.schedules = data
                    } else {
                        this.$bus.alert('error', msg)
                    }
                })
            } else {
                this.schedules = []
            }
        },
        changeDate (val, type) {
            if (val && val !== '') {
                this.appointmentDate = val
                this.loadHealthcare()
            } else {
                this.healthcare = []
            }
        },
        changeTime (val) {
            if (val && val !== '') {
                this.appointmentTime = val
                this.loadHealthcare()
            } else {
                this.healthcare = []
            }
        },
        loadHealthcare () {
            this.formItem.doctorId = ''
            this.formItem.nurseId = ''
            if (this.appointmentDate !== '' && this.appointmentTime !== '') {
                let datetime = this.appointmentDate + ' ' + this.appointmentTime
                let url = '/user/attendance/getHealthcare/' + datetime
                this.$ajax.get(url).then(response => {
                    let {code, data, msg} = response.data
                    if (code === 0) {
                        this.healthcare = data
                    } else {
                        this.$bus.alert('error', msg)
                    }
                })
            } else {
                this.healthcare = []
            }
        },
        // 添加至预约列表
        save () {
            if (this.formItem.patientId !== '') {
                if (this.formItem.type === '') {
                    this.$bus.alert('warning', '请选择预约类型')
                    return
                }
                if (this.formItem.process === '') {
                    this.$bus.alert('warning', '请选择处理方式')
                    return
                }
                // if (this.formItem.remind === '') {
                //     this.$bus.alert('warning', '请选择提醒方式')
                //     return
                // }
                if (this.appointmentDate === '') {
                    this.$bus.alert('warning', '请选择预约日期')
                    return
                }
                if (this.appointmentTime === '') {
                    this.$bus.alert('warning', '请选择预约时间')
                    return
                }
                if (this.formItem.doctorId === '') {
                    this.$bus.alert('warning', '请选择预约医生')
                    return
                }
                if (this.formItem.nurseId === '') {
                    this.$bus.alert('warning', '请选择预约护士')
                    return
                }
                this.data = []
                this.formItem.appointmentStr = this.appointmentDate + ' ' + this.appointmentTime
                if (this.formItem.appointmentStr !== '') {
                    if (this.formItem.process === '2') {
                        let url = this.reservationURL + '/checkAppointment'
                        this.$ajax.post(url, this.formItem).then(response => {
                            let {code, msg} = response.data
                            if (code === 0) {
                                this.data.push(this.formItem)
                                this.doSave()
                            } else {
                                this.$bus.modal('warning', '系统提示', msg)
                            }
                        })
                    } else {
                        this.data.push(this.formItem)
                        this.doSave()
                    }
                } else {
                    this.$bus.modal('error', '系统提示', '操作异常，请联系管理员')
                }
            } else {
                this.$bus.alert('warning', '请选择预约患者')
            }
        },
        doSave () {
            if (this.formItem.id !== '') {
                this.$Modal.confirm({
                    title: '操作提示',
                    content: '<p>确认重新预约?</p>',
                    onOk: () => {
                        let url = this.reservationURL + '/change'
                        this.$ajax.post(url, this.data[0]).then((response) => {
                            let {code, msg} = response.data
                            if (code === 0) {
                                this.close()
                                setTimeout(() => {
                                    this.$bus.modal('success', '系统提示', '重新预约成功')
                                },100)
                            } else {
                                this.$bus.modal('error', '系统提示', msg)
                            }
                        })
                    }
                })
            } else {
                this.$Modal.confirm({
                    title: '操作提示',
                    content: '<p>确认预约?</p>',
                    onOk: () => {
                        let url = this.reservationURL + '/saveAppointment'
                        this.$ajax.post(url, this.data).then((response) => {
                            let {code, msg} = response.data
                            if (code === 0) {
                                setTimeout(() => {
                                    this.$Modal.confirm({
                                        title: '系统提示',
                                        content: '<p>预约成功</p>',
                                        onOk: () => {
                                            this.$bus.init(this.formItem, ['patientId', 'patientName', 'medicalNumber'])
                                            this.schedules = []
                                            this.healthcare = []
                                            this.reset()
                                        }
                                    })
                                }, 100)
                            } else {
                                this.$bus.alert('error', msg)
                            }
                        })
                    }
                })
            }
        },
        changeSelect (selection) {
            this.selectRows = selection
        },
        changeTotalSize (totalSize) {
            this.pageModel1.totalSize = totalSize
        },
        changePageNumber (pageNumber) {
            this.pageModel1.pageNumber = pageNumber
        },
        changePageSize (pageSize) {
            this.pageModel1.pageSize = pageSize
        },
        reset () {
            this.$refs.formItem.resetFields()
        },
        close () {
            this.$bus.closePageToLink()
        },
        init () {
            this.$bus.init(this.formItem)
            // id不为空代表重新预约过来的
            if (this.$route.query.id) {
                let row = this.$route.query
                this.formItem = row
                this.formItem.type = row.type + ''
                this.formItem.remind = row.remind + ''
                this.formItem.process = row.process + ''
                this.formItem.appointment = ''
                this.formItem.doctorId = ''
                this.formItem.nurseId = ''
                this.formItem.expertId = ''
                this.formItem.note = ''
                //表示预约完成后跳转过来的数据
                if (this.$route.query.complete) {
                    this.formItem.id = ''
                }
                // 加载患者信息
                this.searchValue = row.patientName
                let url = '/user/patient/findById/' + row.patientId
                this.$ajax.get(url).then(r => {
                    let {code, data, msg} = r.data
                    if (code === 0) {
                        this.patient = data
                        this.formItem.patientId = data.id
                        this.formItem.patientName = data.name
                        this.formItem.medicalNumber = data.medicalNumber
                    } else {
                        this.$bus.alert('error', msg)
                    }
                })
                // 加载可选时间
                this.changeType(this.formItem.type)
            }
        }
    },
    mounted () {
        this.init()
    },
    watch: {
        '$route' (to) {
            if (to.path === '/reservation/details') {
                this.init()
            }
        }
    }
}
</script>

<style>
.divClass {
    background-color: #fff;
}
</style>
